//
//  SAGetCheckCodeView.m
//  yidiantong
//
//  Created by 黄志刚 on 2020/11/3.
//

#import "SAGetCheckCodeView.h"
#import "SAProductHomeScreeningHeaderView.h"
#import "SAProductHomeScreenCell.h"
#import "SAProductHomeScreeningModel.h"
#import "AFHTTPSessionManager.h"
#import "AFHTTPSessionManager.h"
#import <WebKit/WebKit.h>

@interface SAGetCheckCodeView()<UITextFieldDelegate, WKNavigationDelegate, WKScriptMessageHandler>

@property (nonatomic,strong) SAProductHomeScreeningModel *selectedModel;
@property (nonatomic,strong) UIImageView *backGroundView;
@property (nonatomic,strong) UIImageView *checkCodeView;
@property (nonatomic,strong) UITextField *phoneTextfiled;


@property (nonatomic,strong) UIButton *checkCodeBtn;
@property (nonatomic,copy) NSString *phoneStr;
@end

@implementation SAGetCheckCodeView

+(instancetype)shareCornView
{
    SAGetCheckCodeView * shareView = [[SAGetCheckCodeView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    return shareView;
}

-(instancetype)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame])
    {
        self.userInteractionEnabled = YES;
        self.backgroundColor = kColor(0, 0, 0, 0.6);
        [self creatUI];
        
    }
    return self;
}


-(void)creatUI
{
    UIImageView *backGroundView = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - kScaleNum(300))/2, (kScreenHeight - kScaleNum(100))/2, kScaleNum(300), kScaleNum(100))];
    backGroundView.userInteractionEnabled = YES;
    backGroundView.clipsToBounds = YES;
    backGroundView.layer.cornerRadius = kScaleNum(5);
    [self addSubview:backGroundView];
    self.backGroundView = backGroundView;
    backGroundView.backgroundColor = [UIColor whiteColor];
    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    
    
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(kScaleNum(5), kScaleNum(28), kScaleNum(900), kScaleNum(768)) configuration:config];
     NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://saas.fuyungroup.com/mmv/aliyunNC.html"]];
     [webView loadRequest:request];
     [backGroundView addSubview:webView];
    [webView.configuration.userContentController addScriptMessageHandler:self name:@"verifySuccess"];
    
//     UILabel *hitLabel = [[UILabel alloc] initWithFrame:CGRectMake(size(0), size(48), size(592), size(38))];
//     hitLabel.textAlignment = NSTextAlignmentCenter;
//     hitLabel.textColor = UIColorRGB(51, 51, 51);
//     hitLabel.font = [UIFont boldSystemFontOfSize:size(37)];
//     hitLabel.text = @"输入图形校验码";
//     [backGroundView addSubview:hitLabel];
//
//    UIImageView *textView = [[UIImageView alloc] initWithFrame:CGRectMake(size(59),size(142), size(274), size(61))];
//    textView.image = [UIImage imageNamed:@"login_check_code_text"];
//    textView.userInteractionEnabled = YES;
//    [backGroundView addSubview:textView];
//  //  self.backGroundView = backGroundView;
//
//       UIButton *checkCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        checkCodeBtn.frame = CGRectMake(size(361),size(142), size(185), size(61));
//        checkCodeBtn.titleLabel.font = [UIFont systemFontOfSize:size(45)];
//          [checkCodeBtn setTitle:@"点击刷新" forState:UIControlStateNormal];
//          [checkCodeBtn setTitleColor:UIColorRGB(255, 255, 255) forState:UIControlStateNormal];
//        [checkCodeBtn addTarget:self action:@selector(checkCodeBtnClick) forControlEvents:UIControlEventTouchUpInside];
//        [backGroundView addSubview:checkCodeBtn];
//         self.checkCodeBtn = checkCodeBtn;
//
//            UITextField *phoneTextfiled = [[UITextField alloc] initWithFrame:CGRectMake(size(10), size(2),size(250), size(60))];
//            // phoneTextfiled.backgroundColor = [UIColor whiteColor];
//              phoneTextfiled.keyboardType = UIKeyboardTypeDefault;
//              phoneTextfiled.delegate = self;
//              phoneTextfiled.autocapitalizationType = UITextAutocapitalizationTypeNone;
//              phoneTextfiled.clearButtonMode = UITextFieldViewModeWhileEditing;
//              phoneTextfiled.font = [UIFont systemFontOfSize:size(32)];
//              phoneTextfiled.keyboardType = UIKeyboardTypeDefault;
//              [phoneTextfiled setTintColor:UIColorRGB(178, 178, 178)];
//              [phoneTextfiled setTextColor:UIColorRGB(51, 51, 51)];
//    phoneTextfiled.textAlignment =  NSTextAlignmentCenter;
//             // [phoneTextfiled addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
//              [textView addSubview:phoneTextfiled];
//    self.phoneTextfiled = phoneTextfiled;
//
////    UIImageView *checkCodeView = [[UIImageView alloc] initWithFrame:CGRectMake(size(361),size(142), size(185), size(61))];
////    checkCodeView.backgroundColor = [UIColor cyanColor];
////
////    checkCodeView.userInteractionEnabled = YES;
////    [backGroundView addSubview:checkCodeView];
////    self.checkCodeView = checkCodeView;
//
//       UIButton *cancelCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//      cancelCodeBtn.frame = CGRectMake(size(59),size(243), size(237), size(61));
//         [cancelCodeBtn setBackgroundImage:[UIImage imageNamed:@"login_check_cancel_btn"] forState:UIControlStateNormal];
//             cancelCodeBtn.titleLabel.font = [UIFont systemFontOfSize:size(32)];
//               [cancelCodeBtn setTitle:@"取消" forState:UIControlStateNormal];
//
//               [cancelCodeBtn setTitleColor:UIColorRGB(72, 213, 231) forState:UIControlStateNormal];
//             [cancelCodeBtn addTarget:self action:@selector(cancelCodeBtnClick) forControlEvents:UIControlEventTouchUpInside];
//             [backGroundView addSubview:cancelCodeBtn];
//
//
//            UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//           confirmBtn.frame = CGRectMake(size(310),size(243), size(237), size(61));
//              [confirmBtn setBackgroundImage:[UIImage imageNamed:@"login_check_confirm_btn"] forState:UIControlStateNormal];
//        confirmBtn.titleLabel.font = [UIFont systemFontOfSize:size(32)];
//          [confirmBtn setTitle:@"确认" forState:UIControlStateNormal];
//
//          [confirmBtn setTitleColor:UIColorRGB(255, 255, 255) forState:UIControlStateNormal];
//        [confirmBtn addTarget:self action:@selector(confirmBtnClick) forControlEvents:UIControlEventTouchUpInside];
//        [backGroundView addSubview:confirmBtn];
    
    

    
}

-(void)loadStr:(NSString *)str
{
    self.phoneStr = str;
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
     NSMutableDictionary *headerDict = [[NSMutableDictionary alloc] init];
      dict[@"mobile"] = str;
    
    headerDict[@"mobile"] = str;
      
      AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
      manager.responseSerializer = [AFHTTPResponseSerializer serializer];
      
//      [manager GET:SA_BASE_URL(URL_LOGIN_GET_IMG_CODE) parameters:dict success:^(NSURLSessionDataTask *task, id responseObject) {
//          NSString *result = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
//          UIImage *res =  [UIImage imageWithData:responseObject];
//          NSLog(@"%@",result);
//         [self.checkCodeBtn setImage:res forState:UIControlStateNormal];
//      } failure:^(NSURLSessionDataTask *task, NSError *error) {
//          NSLog(@"%@",error);
//      }];
    [manager GET:SA_BASE_URL(URL_LOGIN_GET_IMG_CODE) parameters:dict headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *result = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
                 UIImage *res =  [UIImage imageWithData:responseObject];
                 NSLog(@"%@",result);
                [self.checkCodeBtn setImage:res forState:UIControlStateNormal];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    
}

-(void)checkCodeBtnClick
{
    [self loadStr:self.phoneStr];
}

-(void)cancelCodeBtnClick
{
    
    [UIView animateWithDuration:0.5f animations:^{
          
          self.alpha = 0.0;
      } completion:^(BOOL finished) {
          [self removeFromSuperview];
      }];
}

-(void)confirmBtnClick
{
    if (self.phoneTextfiled.text.length == 0) {
        [Prompt popPromptViewWithMsg:@"图形校验码不能为空" duration:2];
        return;
    }

    [UIView animateWithDuration:0.5f animations:^{
          
          self.alpha = 0.0;
      } completion:^(BOOL finished) {
          [self removeFromSuperview];
      }];
}

- (void)showView:(UIViewController *)Sview
{
    if(Sview==nil){
        [[UIApplication sharedApplication].keyWindow addSubview:self];
    }else{
        [Sview.view addSubview:self];
    }
}

-(void)shareDissTapEvent
{
    [UIView animateWithDuration:0.5f animations:^{
          
          self.alpha = 0.0;
      } completion:^(BOOL finished) {
          [self removeFromSuperview];
      }];
}

-(void)confirmationTapEvent
{
    [UIView animateWithDuration:0.5f animations:^{
            
            self.alpha = 0.0;
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
        }];
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    CGPoint point = [[touches anyObject] locationInView:self];
    point = [self.backGroundView.layer convertPoint:point fromLayer:self.layer];
    if (![self.backGroundView.layer containsPoint:point]) {
          [UIView animateWithDuration:0.5f animations:^{

                 self.alpha = 0.0;
             } completion:^(BOOL finished) {
                 [self removeFromSuperview];
             }];

    }
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
  
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    NSString *verifySuccess = message.name;
    if ([verifySuccess isEqualToString:@"verifySuccess"]) {
        NSData *jsonData = [message.body dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                            options:NSJSONReadingMutableContainers
                                                              error:&err];
        !self.selectedCodeBlock ?: self.selectedCodeBlock(dic);
    }else if ([verifySuccess isEqualToString:@"verifyFail"]) {
        NSData *jsonData = [message.body dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                            options:NSJSONReadingMutableContainers
                                                              error:&err];
        [Prompt popPromptViewWithMsg:dic[@"msg"] duration:2];
    }else if ([verifySuccess isEqualToString:@"verifyError"]) {
        NSData *jsonData = [message.body dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                            options:NSJSONReadingMutableContainers
                                                              error:&err];
        [Prompt popPromptViewWithMsg:dic[@"msg"] duration:2];
    }else {
        
    }
    [UIView animateWithDuration:0.5f animations:^{
          
          self.alpha = 0.0;
      } completion:^(BOOL finished) {
          [self removeFromSuperview];
      }];
}

@end
